﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace Kanban.Repository
{
    internal static class DataReaderExtensions
    {
        internal static T GetValueOrDefault<T>(this IDataReader reader, int index)
        {
            if (reader.IsDBNull(index))
                return default(T);

            object value = reader.GetValue(index);

            return (T)Convert.ChangeType(value, typeof(T));
        }

        internal static string GetStringOrEmpty(this IDataReader reader, int index)
        {
            if (reader.IsDBNull(index))
                return string.Empty;

            object value = reader.GetValue(index);

            return value.ToString();
        }
    }

    internal static class DbCommandExtensions
    {
        internal static int AddStringOrDBNullParameter(this IDbCommand cmd, string name, string value)
        {
            var p = cmd.CreateParameter();
            p.ParameterName = name;

            if (string.IsNullOrEmpty(value))
                p.Value = DBNull.Value;
            else
                p.Value = value;

            return cmd.Parameters.Add(p);
        }

        internal static int AddInt32OrZero(this IDbCommand cmd, string name, int? value)
        {
            var p = cmd.CreateParameter();
            p.ParameterName = name;

            if (value.HasValue)
                p.Value = value.Value;
            else
                p.Value = 0;

            return cmd.Parameters.Add(p);
        }

        internal static int AddNullableDecimalOrZero(this IDbCommand cmd, string name, decimal? value)
        {
            var p = cmd.CreateParameter();
            p.ParameterName = name;

            if (value.HasValue)
                p.Value = value.Value;
            else
                p.Value = 0;

            return cmd.Parameters.Add(p);
        }
    }
}